package com.goktech.olala.client.controller.backstage;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.goktech.olala.client.controller.basic.BasicController;
import com.goktech.olala.client.controller.basic.ResultStatus;
import com.goktech.olala.core.config.SysConfig;
import com.goktech.olala.core.req.ReqPicture;
import com.goktech.olala.core.resp.RespPictureVo;
import com.goktech.olala.core.service.IPictureService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

/**
 * @author wusq
 * 图片控制器层
 */
@Controller
@RequestMapping(value = "/pictureApi")
public class PictureController extends BasicController {

    @Autowired
    IPictureService pictureService;

    @RequestMapping(value = "/queryPictureList.do")
    @ResponseBody
    public ModelMap queryPictureList(HttpServletRequest request, HttpServletResponse response,
                    Integer sEcho, Integer iDisplayStart, Integer iDisplayLength) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "";

        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            ReqPicture reqPicture = buildReqPicture(params);

            int pageIndex = iDisplayStart / iDisplayLength + 1;
            PageInfo<RespPictureVo> pageInfo = pictureService.queryPictureByParam(reqPicture, pageIndex, iDisplayLength);
            if (pageInfo != null && CollectionUtils.isEmpty(pageInfo.getList())) {
                respCode = ResultStatus.QUERY_NULL.getCode();
                respMsg = ResultStatus.QUERY_NULL.getMsg();
            }
            respData = super.respParamsFormat(respCode, respMsg, sEcho, pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = ResultStatus.BAD_REQUEST.getCode();
            respMsg = ResultStatus.BAD_REQUEST.getMsg();
            respData = super.respParamsFormat(respCode, respMsg, null);
        }
        resultMap.put("respData", respData);
        return resultMap;
    }

    /**
     * 根据主键ID查询图片信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/queryPictureInfoById.do")
    @ResponseBody
    public ModelMap queryPictureInfoById(HttpServletRequest request) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "";

        JSONObject respData = null;
        try {
            JSONObject params = super.reqParamsFormat(request);
            Long pictureId = params.getLong("pictureId");

            RespPictureVo respPictureVo = pictureService.queryPictureById(pictureId);
            respData = super.respParamsFormat(respCode, respMsg, respPictureVo);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = ResultStatus.BAD_REQUEST.getCode();
            respMsg = ResultStatus.BAD_REQUEST.getMsg();
            respData = super.respParamsFormat(respCode, respMsg, null);
        }
        resultMap.put("respData", respData);
        return resultMap;
    }

    /**
     * 图片删除
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/removePictureById.do", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap removePictureById(HttpServletRequest request) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "删除成功";

        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            Long pictureId = params.getLong("pictureId");

            int result = pictureService.removePictureById(pictureId);
            respData = super.respParamsFormat(respCode,respMsg, result);
        } catch (Exception e) {
            e.printStackTrace();
            respData = super.respParamsFormat(SysConfig.ERROR_CODE,"服务异常", null);
        }
        resultMap.put("respData", respData);
        return resultMap;
    }


    /**
     * 图片批量删除
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/removePictureBatch.do", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap removePictureBatch(HttpServletRequest request, HttpServletResponse response) {
        ModelMap resultMap = new ModelMap();
        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            String pictureIds = params.getString("pictureId");

            int result = pictureService.removePictureBatch(pictureIds);
            respData = super.respParamsFormat(SysConfig.SUCCESS_CODE,"删除成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            respData = super.respParamsFormat(SysConfig.ERROR_CODE,"服务异常", null);
        }
        resultMap.put("respData", respData);
        return resultMap;
    }

    /**
     * 图片发布
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/deployPictureById.do", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap deployPictureById(HttpServletRequest request) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "";

        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            Long pictureId = params.getLong("pictureId");
            Integer status = params.getInteger("status");

            int result = pictureService.updatePictureStatus(pictureId, status);
            respData = super.respParamsFormat(respCode,respMsg, result);
        } catch (Exception e) {
            e.printStackTrace();
            respData = super.respParamsFormat(SysConfig.ERROR_CODE,"服务异常", null);
        }
        resultMap.put("respData", respData);
        return resultMap;
    }


    /**
     * 保存图片信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/savePictureInfo.do", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap savePictureInfo(HttpServletRequest request) {

        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "图片保存成功!";

        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            ReqPicture reqPicture = buildReqPicture(params);
            int result = pictureService.savePictureInfo(reqPicture);
            respData = super.respParamsFormat(respCode, respMsg, result);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = SysConfig.ERROR_CODE;
            respMsg = ResultStatus.BAD_REQUEST.getMsg();
            respData = super.respParamsFormat(respCode, respMsg, null);
        }
        resultMap.put("respData", respData);
        return resultMap;
    }


    /**
     * 封装图片公共入参
     *
     * @param params
     * @return
     */
    private ReqPicture buildReqPicture(JSONObject params){
        String select="on";
        Long pictureId = params.getLong("pictureId");
        String pictureTitle = params.getString("pictureTitle");
        String prefTitle = params.getString("prefTitle");
        String relationId = params.getString("relationId");
        String thumbImg = params.getString("thumbImg");
        String realImg = params.getString("realImg");
        String originalImg = params.getString("originalImg");
        String linkUrl = params.getString("linkUrl");
        String keywords = params.getString("keywords");
        String author = params.getString("author");
        String source = params.getString("source");
        String abstracts = params.getString("abstracts");
        String deployTime = params.getString("deployTime");
        String outlineTime = params.getString("outlineTime");
        String width = params.getString("width");
        String height = params.getString("height");
        Integer sortOrl = params.getInteger("sortOrl");
        Integer status = params.getInteger("status");
        Integer relationType = params.getInteger("relationType");
        Integer isMaster = params.getInteger("isMaster");
        String allowComment = params.getString("allowComment");
        Long picCategory = params.getLong("picCategory");
        String picDesc = params.getString("picDesc");
        String imgPathArr = params.getString("imgPathArr");

        ReqPicture reqPicture = new ReqPicture();
        reqPicture.setPictureId(pictureId);
        reqPicture.setPictureTitle(pictureTitle);
        reqPicture.setPrefTitle(prefTitle);
        reqPicture.setAuthor(author);
        reqPicture.setSource(source);
        reqPicture.setAbstracts(abstracts);
        reqPicture.setDeployTime(deployTime);
        reqPicture.setOutlineTime(outlineTime);
        reqPicture.setKeywords(keywords);
        if(select.equals(allowComment)){
            reqPicture.setIsAllowComment(1);
        }
        reqPicture.setRelationId(relationId);
        reqPicture.setPicCategory(picCategory);
        reqPicture.setThumbImg(thumbImg);
        reqPicture.setRealImg(realImg);
        reqPicture.setOriginalImg(originalImg);
        reqPicture.setLinkUrl(linkUrl);
        reqPicture.setWidth(width);
        reqPicture.setHeight(height);
        reqPicture.setSortOrl(sortOrl);
        reqPicture.setStatus(status);
        reqPicture.setRelationType(relationType);
        reqPicture.setIsMaster(isMaster);
        reqPicture.setPicDesc(picDesc);
        String path=",";
        if(StringUtils.isNotBlank(imgPathArr) && imgPathArr.startsWith(path)){
            imgPathArr = imgPathArr.substring(1);
        }
        reqPicture.setImgPathArr(imgPathArr);

        return reqPicture;
    }

}
